#include "header/Prio_Processer.h"
Prio_Processer::Prio_Processer(int n):BaseProcesser(n){
    type=Prio;
}

void Prio_Processer::insert_back()
{
    insert(running);
    if(!readyH)
        readyH=readyT;
}

void Prio_Processer::first_in()
{
    if(readyH){
        running = readyH;
        running->state=State::RUN;
        readyH=readyH->next;
        if(readyH)
            readyH->pre=nullptr;
    }
}
bool Prio_Processer::do_job(){
    running->needtime--;
    running->prio--;
    running->cputime++;
    return running->needtime<=0;
}

void Prio_Processer::do_creat(int needtime){
   
    PCB * p_new=empty;
    empty=empty->next;

    int prio=50-needtime;
    p_new->prio=prio;
    p_new->needtime=needtime;
    p_new->state=State::RDY;
    insert(p_new);
    p_num++;    
}

void Prio_Processer::insert(PCB*p_new){
    PCB * p=readyH;
    int prio=p_new->prio;
    while(p && prio < p->prio){
        p=p->next;
    }

    if(p && p->pre){
       
        p_new->pre=p->pre;
        p_new->next=p;
        p->pre=p_new;

        p_new->pre->next=p_new;

    }else if(!p){
        p_new->next=p;
        p_new->pre=readyT;
        readyT->next=p_new;

        readyT=readyT->next;
        readyT->next=nullptr;
    }else {
        p_new->pre=p->pre; //
        p_new->next=p;
        p->pre=p_new;

        readyH=readyH->pre;
        readyH->pre=nullptr;
    }
}